﻿/**
 * ...
 * @author sminutoli
 */
import com.dmotiko.prune.*
import com.dmotiko.general.*
import com.dmotiko.lib.*
import mx.transitions.easing.Regular;
import mx.transitions.Tween;
import mx.utils.Delegate;

class NewsletterSection extends Section
{
	
	private var mcClose:MovieClip;
	private var mcSend:MovieClip;
	private var sender:LoadVars;
	private var txtMail:TextField;
	private var timer:MovieClip;
	private var mcError:MovieClip;
	
	private var sun_listener:Function;
	
	private function initClip():Void {
		super.initClip();
		
		var root = this;
		
		timer = TimerMovie.createTimer( this );
		
		sender = new LoadVars();
		
		mcSend.onRelease = function(){
			root.validateFields();
		}
		
		sun_listener = Delegate.create(this, sun_hidden);	
		Site.getApp().addEventListener( WebSite.SECTION_CHANGED, Delegate.create( this, section_changed ) );
	}
	
	private function section_changed(e):Void 
	{
		if ( e.section == SiteSections.NEWSLETTER ) {
			Site.getApp().getClips().getSol().addEventListener( BaseClipEvent.CHANGED, sun_listener );			
			
		} else {
			hide();
		}
	}
	
	private function sun_hidden():Void 
	{
		if ( Site.getApp().getSection() != SiteSections.NEWSLETTER ) return;
		Site.getApp().getClips().getSol().removeEventListener( BaseClipEvent.CHANGED, sun_listener );
		show();
	}
	
	private function validateFields():Void {
		if ( FormFieldValidator.mail( txtMail.text ) ) sendMail();
		else registerTween( "errorFade", new Tween( mcError, "_alpha", Regular.easeOut, 30, 0, 0.5, true) );
	}
	
	private function sendMail():Void {
		var root = this;
		sender.email = txtMail.text;
		Site.getApp().log(" NewsletterSection | sendMail | "+_root["url_mail"]+txtMail.text );
		sender.sendAndLoad(_root["url_mail"]+txtMail.text, sender, "POST");
		sender.onLoad = function(b) {
			
			root.gotoAndStop( "OK" );
			if ( _root.analytics ) {
				getURL(_root.analytics+"('suscribeOK')");
			}
			root.timer.startTimer( { delay: 2000, bind: root, listener: Delegate.create( root, root.goBack ) } );
		}
	}
	
	private function goBack():Void {
		Site.getApp().log( "NewsletterSection | goBack ");
		gotoAndStop(1);
		var root = this;
		mcSend.onRelease = function(){
			root.validateFields();
		}
	}
	
}